package org.krivtsun.scanlab;

import org.krivtsun.scanlab.batch.ImageBatch;
import org.krivtsun.scanlab.editor.ImageEditor;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * todo About dlg improvement. Logo and application icon.
 *
 * @author Andrew Krivtsun
 */
class MainFrame extends JFrame {

    private static final String APP_NAME = "ScanLab";
    private static final String APP_VER = "0.1";

    private final ImageBatch batch = new ImageBatch();
    private final ImageEditor editor = new ImageEditor();
    private final StatusBar status = new StatusBar();

    MainFrame() {
        super(APP_NAME);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setJMenuBar(createMenuBar());

        batch.addBatchSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    editor.setImage(batch.getSelectedImage());
                }
            }
        });

        JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        pane.setOneTouchExpandable(true);
        pane.setLeftComponent(batch.createViewComponent());
        pane.setRightComponent(editor.getViewComponent());
        pane.setResizeWeight(0);
        add(pane, BorderLayout.CENTER);

        status.addItem(batch.getStatusBarItem());
        status.addSeparator();
        status.addItem(editor.getViewStatusBarItem());
        status.addSeparator();
        status.addItem(editor.getScaleStatusBarItem());
        status.addSeparator();
        status.addItem(new GcStatusItem().getStatusComponent());

        add(status.getViewComponent(), BorderLayout.SOUTH);
    }

    private JMenuBar createMenuBar() {
        JMenuBar menu = new JMenuBar();
        menu.add(createFileMenu());
        menu.add(createBatchMenu());
        menu.add(editor.getMenu());
        menu.add(createHelpMenu());
        return menu;
    }

    private JMenu createFileMenu() {
        JMenu menu = new JMenu("File");
        menu.setMnemonic('f');
        menu.add(new JMenuItem(batch.getNewBatchAction()));
        menu.addSeparator();
        menu.add(new JMenuItem(createExitAction()));
        return menu;
    }

    private JMenu createBatchMenu() {
        JMenu menu = new JMenu("Batch");
        menu.setMnemonic('b');
        menu.add(new JMenuItem(batch.getAppendPagesAction()));
        menu.add(new JMenuItem(batch.getDeletePagesAction()));
        return menu;
    }

    private JMenu createHelpMenu() {
        JMenu menu = new JMenu("Help");
        menu.setMnemonic('h');
        menu.add(new JMenuItem(createAboutAction()));
        return menu;
    }

    Action createExitAction() {
        Action action = new AbstractAction("Exit") {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        };
        action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("alt X"));
        action.putValue(Action.MNEMONIC_KEY, new Integer('X'));
        return action;
    }

    Action createAboutAction() {
        Action action = new AbstractAction("About...") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(MainFrame.this,
                        new JLabel("<html>" + APP_NAME + " " + APP_VER + "<br>Copyright &copy; 2007 Andrew Krivtsun"),
                        "About", JOptionPane.INFORMATION_MESSAGE);
            }
        };
        action.putValue(Action.MNEMONIC_KEY, new Integer('A'));
        return action;
    }

    private static class GcStatusItem {

        private JComponent status = Box.createHorizontalBox();
        private final Runtime runtime = Runtime.getRuntime();

        private final JLabel label;
        private final JButton button;

        GcStatusItem() {
            label = new JLabel("12345");
            button = createButton();

            Dimension dim = new Dimension(
                    button.getPreferredSize().width,
                    label.getPreferredSize().height);
            button.setPreferredSize(dim);

            status.add(label);
            status.add(Box.createHorizontalStrut(5));
            status.add(button);

            updateStatus();
            startUpdater();
        }

        public JComponent getStatusComponent() {
            return status;
        }

        private JButton createButton() {
//            Icon icon = new ImageIcon(ScanLabApp.class.getResource("icons/gc.png"));
//            JButton button = new JButton(icon);
//            button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
            JButton button = new JButton("GC");
            button.setFocusable(false);
            button.setMargin(new Insets(0, 0, 0, 0));
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.gc();
                }
            });
            return button;
        }

        private void startUpdater() {
            new Timer(1000, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    updateStatus();
                }
            }).start();
        }

        private void updateStatus() {
            double freeMem = runtime.freeMemory();
            double totalMem = runtime.totalMemory();

            double uses = (totalMem - freeMem) / 0x100000L;
            double total = totalMem / 0x100000L;

            label.setText(String.format("%.1fM of %.1fM", uses, total));
        }
    }
}
